﻿/*
 * @author: wizardc
 */

using System;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.Serialization;

namespace Dou.UI
{
    /// <summary>
    /// 接收 Draggable 拖拽的组件
    /// </summary>
    public class Droppable : MonoBehaviour, IDropHandler, IPointerEnterHandler, IPointerExitHandler
    {
        [Serializable]
        public class DropEvent : UnityEvent<Draggable> { }

        /// <summary>
        /// 拖入并释放时
        /// </summary>
        public DropEvent onDropped;

        /// <summary>
        /// 拖入时
        /// </summary>
        public DropEvent onDragEnter;
        
        /// <summary>
        /// 拖出时
        /// </summary>
        public DropEvent onDragExit;

        private bool GetDraggable(PointerEventData eventData, out Draggable draggable)
        {
            if (!eventData.dragging)
            {
                draggable = null;
                return false;
            }
            var dragObj = eventData.pointerDrag;
            if (dragObj == null)
            {
                draggable = null;
                return false;
            }
            draggable = dragObj.GetComponent<Draggable>();
            return draggable != null;
        }
        
        public void OnDrop(PointerEventData eventData)
        {
            if (GetDraggable(eventData, out var draggable))
            {
                onDropped?.Invoke(draggable);
            }
        }

        public void OnPointerEnter(PointerEventData eventData)
        {
            if (GetDraggable(eventData, out var draggable))
            {
                onDragEnter?.Invoke(draggable);
            }
        }

        public void OnPointerExit(PointerEventData eventData)
        {
            if (GetDraggable(eventData, out var draggable))
            {
                onDragExit?.Invoke(draggable);
            }
        }
    }
}
